﻿
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sproc_File_GetDirectoryInfo_V2]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[sproc_File_GetDirectoryInfo_V2];
GO

CREATE PROCEDURE [dbo].[sproc_File_GetDirectoryInfo_V2]
    @ownerId     int,
    @directoryId int
AS
BEGIN
SET NOCOUNT ON;

IF ( @directoryId <= 0 )
BEGIN
    -- get the id of the root directory
    SELECT @directoryId = DirectoryId
        FROM dbo.UDS_File_Directory
        WHERE OwnerId = @ownerId AND ParentDirectoryId = DirectoryId;

    IF ( @@ROWCOUNT = 0 )
    BEGIN
        -- the root directory is missing
        RETURN 0;
    END
END

-- get the information of the given directory
SELECT *
    FROM dbo.UDS_File_Directory
    WHERE DirectoryId = @directoryId AND OwnerId = @ownerId;
IF ( @@ROWCOUNT <> 1 )
    RETURN -1; -- the given directory does not exist

-- get the sub directories
SELECT *
    FROM dbo.UDS_File_Directory
    WHERE
        ParentDirectoryId = @directoryId
        AND OwnerId = @ownerId
        AND (ParentDirectoryId <> DirectoryId) -- exclude the root directory;

-- get the files within the directory
SELECT *
    FROM dbo.UDS_File_File
    WHERE DirectoryId = @directoryId

RETURN 0;
END
GO

